<?php

namespace App\Console\Commands;

use App\Consts\DingTalkConst;
use App\Consts\MessageConfigConst;
use App\Consts\SmsConst;

class UpdateMessageConfigCommand extends BaseCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'msg-config:update';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Update message config for scenes.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handler()
    {
        // update sms config
        $this->update(MessageConfigConst::MSG_CONFIG_KEY_SMS_TYPE, SmsConst::SMS_TEMPLATE_LIST, '短信消息类型');
        // update dingtalk config
        $this->update(MessageConfigConst::MSG_CONFIG_KEY_DINGTALK_TYPE, DingTalkConst::DINGTALK_TEMPLATE_LIST, '钉钉消息类型');
        return true;
    }

    /**
     * update config
     *
     * @param $type
     * @param $config
     * @param $remark
     * @return int
     */
    protected function update($type, $config, $remark)
    {
        $info = service()->MsgConfigService->getConfig($type);
        $info = json_decode($info, true) ?: [];
        $data = [];
        foreach ($config as $key => $val) {
            $data[] = $val;
        }
        if (empty($info)) {
            $this->logger("[INF] insert [$type] config : " . json_encode($data, JSON_UNESCAPED_UNICODE));
            // add config
            repository()->MsgConfigRepository->insert([
                'item' => $type,
                'value' => json_encode($data, JSON_UNESCAPED_UNICODE),
                'remark' => $remark
            ]);
        }
        // update
        $this->logger("[INF] update [$type] config : " . json_encode($data, JSON_UNESCAPED_UNICODE));
        return repository()->MsgConfigRepository->updateInfoByWhere(['item' => $type], [
            'item' => $type,
            'value' => json_encode($data, JSON_UNESCAPED_UNICODE),
            'remark' => $remark
        ]);
    }

}
